import re

from django.shortcuts import render

# Create your views here.
from django_redis import get_redis_connection
from rest_framework import mixins
from rest_framework import serializers

from rest_framework import status
from rest_framework.decorators import action
from rest_framework.generics import GenericAPIView, CreateAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import GenericViewSet

from goods.models import SKU
from users import constants
from users import serializerss
from users.models import User, Address

#　判断用户名是否重复
#　接口/usernames/(?P<username>\w[5,20]/count/)
from users.serializerss import UserSerializer, UserDetialSerializer, EmailSerializer, BrowseHistorySerializer, \
    SKUSerializer


class UserNameCountView(APIView):
    def get(self,requeset,username):
        # 比较数据库中该用户名存在的数量
        count = User.objects.filter(username=username).count()
        # 返回数据
        res = {
            'username':username,
            'count':count
        }

        return Response(res)
# 检测手机号是否重复
#　接口/mobiles/(?P<mobile>1[3-9]\d{9}/count/)
class MobileCountView(APIView):
    def get(self,requeset,mobile):
        # 比较数据库中该手机号存在的数量
        count = User.objects.filter(mobile=mobile).count()
        # 返回数据
        res = {
            'username':mobile,
            'count':count
        }

        return Response(res)

#　保存用户注册信息
# POST /users/
#　后端代码优化
class UserView(CreateAPIView):
    # # 制定视图所使用的序列化器类
    # # serializer_class = UserSerializer
    # # def post(self,request):
    #     """
    #     用户注册信息的保存
    #     # １.获取参数并进行校验（是否同意协议，用户名不能全部是数字，两次密码是否一致，手机号格式，手机号是否存在）
    #     # ２.创建新用户并保存到数据库
    #     # ３.注册成功，将新用户序列化并返回
    #     # """
    #
    #     # 用户注册信息的保存
    #     # １.获取参数并进行校验（是否同意协议，两次密码是否一致，手机号格式，手机号是否存在）
    #     # serializer = self.get_serializer(data=request.data)
    #     # serializer.is_valid(raise_exception =True)
    #     # ２.创建新用户并保存到数据库
    #     # serializer.save()
    #     # ３.注册成功，将新用户序列化并返回
    #     # return Response(serializer.data,status=status.HTTP_201_CREATED)
    #
    # #后端代码优化
    serializer_class = serializerss.UserSerializer


# 获取用户个人信息显示
#　GET /user/
class UserDetialView(GenericAPIView):
    """
    1.获取前端传过来的jwt token 进行验证
    2.将用户数据序列化返回
    """
    serializer_class = serializerss.UserDetialSerializer
    #添加Django自带的权限认证，
    permission_classes = [IsAuthenticated]

    def get(self,request):
        # 1.获取前端传过来的user进行验证
        user = request.user
        # 2.将用户数据序列化返回
        serializer = self.get_serializer(user)
        return Response(serializer.data)


# 设置邮箱 PUT /email/
class EmailView(GenericAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = EmailSerializer


    def put(self,request):
        """
        登录用户邮箱设置
        1.获取参数并进行校验（email必传，email格式校验）
        2.设置用户的邮箱并且给邮箱发送验证邮件
        3.返回响应，邮箱设置成功
        """
        # #登录用户获取
        user = request.user
        # 1.获取参数并进行校验（email必传，email格式校验）
        serializer = self.get_serializer(user,data=request.data)
        serializer.is_valid(raise_exception=True)
        # 2.设置用户的邮箱并且给邮箱发送验证邮件(update)
        serializer.save()
        # 3.返回响应，邮箱设置成功
        return Response(serializer.data)

# PUT /emails/verification/?token=<加密用户的信息>
class EmailVerifyView(APIView):
    def put(self, request):
        """
        用户邮箱验证:
        1. 获取token并进行校验(token必传，token是否有效)
        2. 设置对应用户的邮箱验证标记email_active为True
        3. 返回应答，验证成功
        """
        # 1. 获取token并进行校验(token必传，token是否有效)
        token = request.query_params.get('token') # None

        if token is None:
            return Response({'message': '缺少token参数'}, status=status.HTTP_400_BAD_REQUEST)

        # 对token进行解密
        user = User.check_email_verify_token(token)

        if user is None:
            return Response({'message': '无效的token'}, status=status.HTTP_400_BAD_REQUEST)

        # 2. 设置对应用户的邮箱验证标记email_active为True
        user.email_active = True
        user.save()

        # 3. 返回应答，验证成功
        return Response({'message': 'OK'})


# 地址信息的增删改查
class AddressViewSet(mixins.CreateModelMixin, mixins.UpdateModelMixin, GenericViewSet):
    """
    用户地址新增与修改
    """
    serializer_class = serializerss.UserAddressSerializer
    permissions = [IsAuthenticated]

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # POST /addresses/
    def create(self, request, *args, **kwargs):
        """
        保存用户地址数据
        """
        # 检查用户地址数据数目不能超过上限
        count = request.user.addresses.filter(is_deleted=False).count()
        if count >= constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message': '保存地址数据已达到上限'}, status=status.HTTP_400_BAD_REQUEST)

        return super().create(request, *args, **kwargs)

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializerss.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)
# 在users/serializers.py中添加序列化器

class UserAddressSerializer(serializers.ModelSerializer):
    """
    用户地址序列化器
    """
    province = serializers.StringRelatedField(read_only=True)
    city = serializers.StringRelatedField(read_only=True)
    district = serializers.StringRelatedField(read_only=True)
    province_id = serializers.IntegerField(label='省ID', required=True)
    city_id = serializers.IntegerField(label='市ID', required=True)
    district_id = serializers.IntegerField(label='区ID', required=True)

    class Meta:
        model = Address
        exclude = ('user', 'is_deleted', 'create_time', 'update_time')

    def validate_mobile(self, value):
        """
        验证手机号
        """
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('手机号格式错误')
        return value

    def create(self, validated_data):
        """
        保存
        """
        validated_data['user'] = self.context['request'].user
        return super().create(validated_data)


class AddressTitleSerializer(serializers.ModelSerializer):
    """
    地址标题
    """
    class Meta:
        model = Address
        fields = ('title',)



# 用户中心用户浏览记录商品的展示
# POST /browse_histories/
class BrowseHistoriesView(GenericAPIView):
    permission_classes = [IsAuthenticated]
    serializer_class = BrowseHistorySerializer
    """
    1.获取商品sku_id(sku_id必传,sku_id是否存在)
    2.将用户的浏览记录和对应的sku_id以列表的形式保存到redis中
    3.返回响应，浏览记录添加成功
    """
    def post(self,request):
        # 1.获取商品sku_id(sku_id必传, sku_id是否存在)
        serializer = self.get_serializer(data =request.data)
        serializer.is_valid(raise_exception=True)
        # 2.将用户的浏览记录和对应的sku_id以列表的形式保存到redis中
        serializer.save()
        # 3.返回响应，浏览记录添加成功
        return Response(serializer.data,status=status.HTTP_201_CREATED)
#　浏览记录的获取
# GET
    def get(self,request):
        redis_conn = get_redis_connection("histories")
        history_key = "history_%s"% request.user.id
        sku_ids = redis_conn.lrange(history_key,0,-1)
        skus = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            skus.append(sku)
        serializer = SKUSerializer(skus,many =True)
        return Response(serializer.data)




